--
-- Author: mm
-- Date: 2018-03-20 18:07:43
--
-- NewActivityDungeonsView2
-- 新版活动玩法入口UI

local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local Armature = app:getClass("Armature")
local UIUtil = require("app.utils.UIUtil")

local imgNum = 3 -- 玩法入口个数

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.NewActivityDungeonsScene

local string_split = string.split

-- data = GD:getWorldConfs()
function ClassRef:init()
	-- 关闭按钮
	self._ui.Button_close:addClickEventListener(function()
		executeFunc(self._onCloseView)
	end)

    -- 宝箱
    self._bomPanel = self._ui.Panel_bom
    self.boxNode = self._bomPanel:getChildByName("Panel_icon")
    self.boxLoadingBar = self._bomPanel:findChild("bar/LoadingBar")
    self.boxExpNode = self._bomPanel:getChildByName("exp")
    self._boxIcon = self._bomPanel:findChild("Panel_icon/icon")
    display.uiAddClick(self._boxIcon, function()
        if self.haveNum and self.haveNum > 0 then --预览宝箱
            executeFunc(self._onOperate, "activityDungeons_getReward")
        else -- 宝箱tips
            local dataTemp = GD:queryRestrictedRewardShowById(4)
            self:_showRareInfo(dataTemp, self._boxIcon)
        end
    end)

    -- 活动
    local panels = {}
	for i = 1, imgNum do
        local panel = self._ui["Panel/Panel_m/Panel_Content/Panel_" .. (i+1)]
		display.uiAddClick(panel, function()
			self:_selectedTarget(i)
		end, true, 0.02)
        panels[i] = panel
	end
    self._panels = panels

    -- 挑战赛
    local panel = self._ui["Panel/Panel_m/Panel_Content/Panel_1"]
    self._bgIcon = panel:getChildByName("img_1")
    self._tltText = panel:getChildByName("tlt")
    self._dateText = panel:getChildByName("date")
    self._nameText = panel:getChildByName("tips")
    self._timeBg = panel:getChildByName("bg2")
    self._timeText = panel:getChildByName("time")
    self._openIcon = panel:getChildByName("img_open")
    self._closeIcon = panel:getChildByName("Image_lock")

    self._rankIcon = panel:findChild("Panel_load/btn_icon")
    self._rankText = panel:findChild("Panel_load/ranking")
    self._expBar = panel:findChild("Panel_load/LoadingBar")
    self._expNum = panel:findChild("Panel_load/num")

    local initScale = panel:getScale()
    local scale = 0.02
    display.uiAddClick(
        panel:getChildByName("click"),
        function()
            executeFunc(self._onOperate, "activityDungeons_openFunc", Constant.FUNC_TYPE_CHALLENGE)
        end,
        false,
        nil,
        function(isTouch)
            if isTouch then
                panel:setScale(initScale - scale)
            else
                panel:runAction(cc.ScaleTo:create(0.05, initScale))
            end
        end)

    display.uiAddClick(self._rankIcon, function()
        self:_showChallengeTips()
    end)
end

function ClassRef:show()
    self.super.show(self)

    self:refreshEventBoxInfo()
    self:checkGuide()
end

-- 检查是否触发了引导
function ClassRef:checkGuide()
    local funcId = Constant.FUNC_TYPE_ACTIVITY_DUNGEONS
    local params = {
        scene = funcId,
        sceneSelf = self,
        getFunc = self.getGuideNodeFunc,
        nextFunc = self.checkGuide
    }
    EM:notify("checkGuide", params)
end
-- 获取引导node
function ClassRef:getGuideNodeFunc(id)
    if id == 172 or id == 174 then
        -- 选择 活动-宝箱
        return self._boxIcon
    end
end

-- 选择了具体的玩法入口
function ClassRef:_selectedTarget( idx )
    if not self._targets then return end
    local target = self._targets[idx]
    local funcId
    if target:getId() == Enums.TeamTarget.lionHeart then
        funcId = Constant.FUNC_TYPE_ACTIVITY_DUNGEONS_LIONHEART
    elseif target:getId() == Enums.TeamTarget.ashInvade then
        funcId = Constant.FUNC_TYPE_ACTIVITY_DUNGEONS_ASHINVADE
    elseif target:getId() == Enums.TeamTarget.training then
        funcId = Constant.FUNC_TYPE_ACTIVITY_DUNGEONS_TRAINING
    end
    if funcId then
        executeFunc(self._onOperate, "activityDungeons_openFunc", funcId)
    end
end

-- 刷新副本剩余次数
-- targets = {TeamTarget, ...} 活动副本的TeamTarget列表
function ClassRef:refreshTargets(targets)
    self._targets = targets
    local strTemp = L("left_times")
    for i,target in ipairs(targets) do
        local panel = self._panels[i]
        local tips = panel:findChild("tips")
        local img = panel:findChild("img_1")
        local tlt = panel:findChild("tlt")
        local tltBg = panel:findChild("bg_tlt")

        local isOpen = target:isOpen()
        local restTiems = target:getRestRewardNum()

        img:loadTexture(target:getBanner())
        tlt:setString(target:getName())

        if isOpen then
            if target:isRewardNumLimit() then
                tips:setVisible(true)
                tips:setString(string.format(strTemp, restTiems))
            else
                tips:setVisible(false)
            end
            tltBg:setColor(cc.c4b(0, 0, 0, 200))
            tlt:setTextColor(cc.c3b(255,225,132))
            tips:setTextColor(cc.c3b(145,255,145))
        else
            tltBg:setColor(cc.c4b(64,45,27, 255))
            tlt:setTextColor(cc.c3b(255,232,202))
            tips:setVisible(true)
            tips:setTextColor(cc.c3b(255,232,202))
            tips:setString(string.format(L("openLvShow"), target:getOpenLv()))
        end
    end
end

-- challengeInfo = PvpChallengeSeasonInfo
function ClassRef:refreshChallengeInfo(challengeInfo)
    self._challengeInfo = challengeInfo
    self._bgIcon:loadTexture(challengeInfo:getBanner())
    self._tltText:setString(challengeInfo:getFullTitle())
    self._dateText:setString(challengeInfo:getDateStr())
    self._nameText:setString(challengeInfo:getTargetName())

    self._rankIcon:loadTexture(challengeInfo:getLvIcon())
    self._rankText:setString(string.format(L("赛季等级: %s"), challengeInfo.lv))

    local curScore, needScore = challengeInfo:getScore()
    self._expNum:setString(string.format("%d/%d", curScore, needScore))
    self._expBar:setPercent(curScore * 100 / needScore)
end

-- local data = {}
-- data.isOpen = msg.isOpen
-- data.playId = msg.playId
-- data.startTime = msg.startTime
-- data.endTime = msg.endTime
-- data.state = msg.state
-- data.startMatchStamp = msg.startMatchStamp
function ClassRef:refreshChallengeStatus(challengeStatus)
    local isOpen = challengeStatus.isOpen
    self._openIcon:setVisible(isOpen)
    self._closeIcon:setVisible(not isOpen)
    self._timeBg:setVisible(not isOpen)
    self._timeText:setVisible(not isOpen)

    if not isOpen then
        local serverTime = math.floor(app:getServerTime())
        local szTimes = string.split(GD:getSystemStrPar("challengeGameTime"), "|")
        local timeStr = szTimes[1]
        local ret = TimeUtil.checkTimeInRange(serverTime, szTimes[1])
        if ret == 1 then
            timeStr = szTimes[2]
        end

        local zoneOffset = app.session:getTimeZoneOffset()
        timeStr = TimeUtil.convertTimeStrByTimeZone(timeStr, zoneOffset)
        self._timeText:setString(timeStr)
    end

    -- 入口动画
    self._openIcon:stopAllActions()
    if isOpen then
        local action = cca.repeatForever(cca.rotateBy(2, 360))
        self._openIcon:runAction(action)
    end
end

------------------------ 宝箱/动画 start ---------------------
function ClassRef:_showChallengeTips()
    if not self._challengeInfo then return end
    
    local dataTemp = {
        name = L("seasonlv_name"),
        desc = L("challengeSeasonTips"),
        notice = L("tips_3000412"),
    }
    local rewards = {}
    local level = self._challengeInfo.lv
    if level > 0 then
        local conf = GD:getChallengeLevelInfo(level)
        if conf then
            local dropIds = string.split(conf.seasonReward, ";")
            for _, dropId in ipairs(dropIds) do
                local rets = UD:parseDropIDToBagItem(dropId)
                if rets then
                    for _, itemData in ipairs(rets) do
                        table.insert(rewards, itemData)
                    end
                end
            end
        end
    end
    dataTemp.rewards = rewards
    UIUtil.showBoxTipsView(self, self._rankIcon, dataTemp)
end

------------------------ 宝箱/动画 start ---------------------
-- 展示上方宝物具体信息
function ClassRef:_showRareInfo( dataTemp, triggerNode )
	if self._rareInfoPanel then
		self._rareInfoPanel:setData( dataTemp )
	else
		self._rareInfoPanel = NewRareInfoView.create()
		self._rareInfoPanel:setData( dataTemp )
		self._ui["Panel"]:addChild( self._rareInfoPanel )

		-- 点击空白区域关闭
		display.nodeRemoveForNotHit(self._rareInfoPanel, function()
			if self._rareInfoPanel then
				self._rareInfoPanel:removeFromParent()
				self._rareInfoPanel = nil
			end
		end)
	end

	local triggerNodeBoundingBox = triggerNode:getBoundingBox()
	local worldPosTemp = triggerNode:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
	triggerNodeBoundingBox.x = worldPosTemp.x
	triggerNodeBoundingBox.y = worldPosTemp.y
	display.adjustNodePos( triggerNodeBoundingBox, self._rareInfoPanel )
end

-- 宝箱信息
function ClassRef:refreshEventBoxInfo()
	self.haveNum = UD:getEventLuckBox() -- 宝箱个数
	self.curPoint = UD:getActivityDungeonsPoint() -- 剩余点数
	self.maxPoint = UD:getLuckBoxLevelUpPoint(Enums.BoxType.eventBox) -- 一个宝箱需要的最大点数
	self._curPointCount = self.curPoint + self.haveNum * self.maxPoint
	if UD:hasEventLuckBoxCache() then -- 有宝箱数变化播放动画
		self:playBoxAction()
		UD:clearLuckBoxCacheByKey(Enums.lootType.eventLuckBox) -- 取到缓存数据后要清掉
		UD:clearLuckBoxCacheByKey(Enums.lootType.eventPoint)
	else
		if UD:onlyEventLuckBoxChange() then
			UD:clearLuckBoxCacheByKey(Enums.lootType.eventLuckBox)
			self:performWithDelay(function()
				self:_playBoxArmature()
			end, 0.05)
		end
		self:_refreshBoxInfo()
	end
end

-- 初始化宝箱动画
local boxNum = 0
local boxNumCache = 0
local playTimes = -1
local barStart = 0
local barEnd = 0
local startPer = 0
local endPer = 0
local per = 2
function ClassRef:playBoxAction()
	local pointCountCache = UD:getEventPointCache()
	local isBoxChange = pointCountCache and pointCountCache ~= self._curPointCount
	if isBoxChange then
		boxNum = math.floor(pointCountCache / self.maxPoint)
		boxNumCache = boxNum
		playTimes = self.haveNum - boxNum
		barStart = pointCountCache % self.maxPoint
		barEnd = playTimes > 0 and self.maxPoint or (barStart + self._curPointCount - pointCountCache)
		startPer = math.ceil(barStart * 100 / self.maxPoint)
		endPer = math.ceil(barEnd * 100 / self.maxPoint)

		self:_refreshBoxInfo(boxNum, barStart)
		self:playBoxBarAni()
    else
        self:_refreshBoxInfo()
	end
end

-- 播放经验条动画
function ClassRef:playBoxBarAni()
	self.boxLoadingBar:schedule(function()
		startPer = math.min(startPer + per, endPer)
		if playTimes < 0 then
			self.boxLoadingBar:stopAllActions()
		else
			if startPer == endPer then
				-- 达到最大值，先停止动画，然后播放宝箱闪光特效，修改宝箱个数
				boxNum = math.min(boxNum + 1, self.haveNum)
				playTimes = playTimes - 1
				barStart = playTimes < 0 and self.curPoint or 0
				barEnd = playTimes <= 0 and self.curPoint or self.maxPoint
				startPer = math.ceil(barStart * 100 / self.maxPoint)
				endPer = math.ceil(barEnd * 100 / self.maxPoint)
				self:_refreshBoxInfo(boxNum, barStart)
				if boxNumCache ~= boxNum then
					self:_playBoxArmature()
					boxNumCache = boxNum
				end
			else
				self.boxLoadingBar:setPercent(startPer)
				local point = math.floor(startPer / 100 * self.maxPoint)
				self.boxExpNode:setString(table.concat({point, "/", self.maxPoint}))
			end
		end
	end, 0.05)
end

-- 播放宝箱特效
function ClassRef:_playBoxArmature()
	if not self._inArmature then
		local params = {
			armatureName = "shaizibengchu",
			path = Res.ChessRollInEfcPath
		}
		local armature = Armature.create(params)
		local posX, posY = self.boxNode:getChildByName("Node_ani"):getPosition()
		self.boxNode:addChild(armature)
		armature:setPosition(posX, posY)
		armature:setScale(0.3, 0.3)
		self._inArmature = armature
	end
	self._inArmature:setVisible(true)
	self._inArmature:play("shaizibengchu", 1, function(sender)
		sender:setVisible(false)
		self:playBoxBarAni()
	end)
end

-- 刷新宝箱累积进度
function ClassRef:_refreshBoxInfo(boxNum, point)
    if not boxNum then
        boxNum = self.haveNum
    end
    if not point then
        point = self.curPoint
    end
    local maxAccumulateBoxNum = tonumber( GD:getSystemPar( "eventBoxAccumulateLimited", 20 ) ) -- 累积的上限
    -- 宝箱个数
    self.boxNode:findChild("bg_num/num"):setString(boxNum)
    self:_refreshBoxNumBg(boxNum > 0)
    self.boxNode:getChildByName("tips_max"):setVisible( maxAccumulateBoxNum <= boxNum )
    self._ui.tlt_2:setString(L("restrictedreward6_surface"))

    if 0 < boxNum then
        self:playAction( "box", true )
    else
        self:pauseAction()
    end
    -- 经验条
    local percent = math.floor(point/self.maxPoint*100)
    self.boxLoadingBar:setPercent(percent)
    self.boxExpNode:setString(table.concat({point, "/", self.maxPoint}))
end

function ClassRef:_refreshBoxNumBg(isShow)
    local remainDayTimes = UD:getLuckBoxRestTimesByType(Enums.BoxType.eventBox) --剩余每日开启次数
    local remainWeekTimes = UD:getLuckBoxWeeklyRestTimesByType(Enums.BoxType.eventBox) -- 剩余每周开启次数
    local redBg = self.boxNode:findChild("bg_num/bg")
    local blackBg = self.boxNode:findChild("bg_num/bg_1")
    if isShow then
        if remainDayTimes > 0 and remainWeekTimes > 0 then
            redBg:setVisible(true)
            blackBg:setVisible(false)
        else
            redBg:setVisible(false)
            blackBg:setVisible(true)
        end
    end
    self.boxNode:getChildByName("bg_num"):setVisible(isShow)
    self.boxNode:getChildByName("mask"):setVisible(not isShow)
    self.boxNode:getChildByName("lock"):setVisible(not isShow)
end
------------------------ 宝箱/动画 end ---------------------

return ClassRef
